﻿using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SaiLing.Cache;
using SaiLing.SingleSignOn.Domain.Entities.DataTransferObject;
using SaiLing.Web;
using SaiLing.SingleSignOn.Application.Service;

namespace SaiLing.SingleSignOn.Application.Core.Authorizations
{
    public class AuthorizationHelper
    {
        private static ICacheService CacheService => ServiceFactory.GetService<ICacheService>();

        public static Task<SiginUser> Get()
        {
            var user = CookieUser() ?? CacheUser();
            return Task.FromResult(user);
        }

        private static SiginUser CookieUser()
        {
            var user = HttpContext.Current.User.Claims.FirstOrDefault(x => x.Type == "user");
            if (user == null)
                return null;
            var result = JsonConvert.DeserializeObject<SiginUser>(user.Value);
            return result;
        }

        private static SiginUser CacheUser()
        {
            var list = HttpContext.Current.Request.Headers.ToDictionary(k => k.Key, v => string.Join(';', v.Value.ToList()));
            //var ss=  ((Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameRequestHeaders) HttpContext.Current.Request
            //      .Headers).HeaderAuthorization[0];
            var token = list.FirstOrDefault(x => x.Key == "Authorization");
            if (token.Equals(null))
                return null;

            return CacheService.Get<SiginUser>(token.Value);
        }
    }
}
